package spring.cloud.service.task.analyzer;


import spring.cloud.tasks.common.curator.Curator;
import spring.cloud.tasks.common.curator.CuratorInfo;
import spring.cloud.tasks.common.nodepaths.TaskNodePaths;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class TaskStatisticsAnalyzer {

    private final Map<String/** {taskId}-{domain} */, TaskStatistics> taskKeyToTaskStatisticsMap = new ConcurrentHashMap<>();

    public TaskStatistics analyzeTaskStatistics(Curator curator, CuratorInfo curatorInfo, String taskId, ExecutorInfoAnalyzer executorInfoAnalyzer) throws Exception {
        String jobDomainKey = curatorInfo.getNamespaceKey() + "-" + taskId;
        TaskStatistics taskStatistics = taskKeyToTaskStatisticsMap.get(jobDomainKey);
        if (taskStatistics == null) {
            taskStatistics = new TaskStatistics(curatorInfo.getNamespaceKey(), taskId);
            taskKeyToTaskStatisticsMap.put(jobDomainKey, taskStatistics);
        }
        // loadLevel of this job
        int loadLevel = Integer.parseInt(curator.getData(TaskNodePaths.getTaskBaseInfoNodePath(taskId, "loadLevel")));
        int shardingTotalCount = Integer.parseInt(curator.getData(TaskNodePaths.getTaskBaseInfoNodePath(taskId, "shardingTotalCount")));
        List<String> executorIdList = null;
        if (curator.checkExists(TaskNodePaths.getTaskExecutorsNodePath(taskId))) {
            executorIdList = curator.getChildren(TaskNodePaths.getTaskExecutorsNodePath(taskId));
            executorInfoAnalyzer.analyzeTaskExecutor(curator, curatorInfo, executorIdList, taskId, loadLevel, taskStatistics);
        }

        taskStatistics.setTotalLoadLevel(loadLevel * shardingTotalCount);
        taskKeyToTaskStatisticsMap.put(jobDomainKey, taskStatistics);
        return taskStatistics;
    }

    public List<TaskStatistics> getTaskStatisticsList() {
        return new ArrayList<TaskStatistics>(taskKeyToTaskStatisticsMap.values());
    }
}
